import { finalize, tap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {  HttpInterceptor, HttpHandler, HttpRequest,HttpResponse } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { AuthTokenService } from '../services/auth-token.service';
import { CommonService,ToastColor } from '../services/common-service.service';
import { EncryptService } from '../services/encrypt.service';

@Injectable()
export class SurroundInterceptor implements HttpInterceptor {

  private authRequest:HttpRequest<any>;

  constructor(private authTokenService:AuthTokenService,
              private encryptService:EncryptService,
              private commonService:CommonService) {
      
  }

  getAuthRequest(request: HttpRequest<any>){
    this.authRequest = request.clone();
    let currentTime = new Date().getTime();
    let deviceId = this.authTokenService.getDeviceId();
    if(request.url == '/scm/app/checkAppUserExists.do' 
        || request.url == '/scm/app/checkAppUserExistsByMobile.do'
        || request.url == '/scm/app/getAppAgreement.do'
        || request.url == '/scm/app/saveAppUser.do'
        || request.url == '/scm/app/getAppParam.do'){
        let sign1 = this.encryptService.md5Ecrypt(deviceId+currentTime);
        let sign2 = this.encryptService.rsaEcrypt(deviceId+","+currentTime);
        this.authRequest = request.clone({
          headers: request.headers.set('sign1',sign1).set('sign2',sign2)
        });
    }else{
        let sign1 = request.headers.get("sign1");
        if(!sign1){
          sign1 = this.encryptService.md5Ecrypt(this.authTokenService.getAppUserId()+deviceId+currentTime);
        }
        let sign2 = request.headers.get("sign2");
        if(!sign2){
          sign2 = this.encryptService.rsaEcrypt(this.authTokenService.getAppUserId()+","+deviceId+","+currentTime);
        }
        let userToken = this.authTokenService.getUserToken();
        this.authRequest = request.clone({
          headers: request.headers.set(environment.USER_TOKEN,userToken)
                                  .set('sign1',sign1)
                                  .set('sign2',sign2)
        });
    }
  }

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const started = Date.now();
    let ok: string;
    this.getAuthRequest(request);
    let url = this.authRequest.url;
    if(!url.startsWith('/assets/')){
      this.authRequest = this.authRequest.clone({
        url:environment.URL_PREFIX+url
      });
    }
    return next.handle(this.authRequest)
      .pipe(
        tap(
          event => {
            ok = event instanceof HttpResponse ? 'succeeded' : ''
          },
          errorResp => {
            ok = 'failed'
            console.error("surround-interceptor.ts",errorResp);
            if(!errorResp.error){
              errorResp['error'] = {'errorCode':'system_error','errorMsg':'system error'}
            }else{
              this.authTokenService.disposeErrorForInterceptor(url,errorResp);
            }
          }
        ),
        finalize(() => {
          const elapsed = Date.now() - started;
          const msg = `${request.method} "${request.urlWithParams}"  ${ok} in ${elapsed} ms.`;
          console.log(msg);
        })
      );
  }
}